import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import 'package:rembercount/controller/authLoginController.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:rembercount/pages/main_page.dart';
import 'package:rembercount/pages/settings_page.dart';
import 'package:rembercount/controller/themeController.dart';
import 'package:rembercount/controller/categoryController.dart';
import 'package:rembercount/components/transaction_details_card.dart';
import 'package:rembercount/services/import_service.dart';

void main() => runApp(FinanceApp());

class FinanceApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF2D9596),
          secondary: const Color(0xFF9AD0C2),
        ),
        useMaterial3: true,
      ),
      home: const MainPage(),
    );
  }
}

class Homepage extends StatefulWidget {
  Homepage({super.key});

  @override
  State<Homepage> createState() => _HomepageState();
  final dio = Dio(
    BaseOptions(
      baseUrl: const String.fromEnvironment(
        'BASE_URL',
        defaultValue: "http://localhost:8080",
      ),
    ),
  );
  fet() async {
    var rsp = await dio.get("/test");
    print('rsp:${rsp.data}');
  }
}

class _HomepageState extends State<Homepage> {
  RxBool _isCloseChatr = false.obs;
  CountController countController = Get.find<CountController>();
  Authlogincontroller authlogincontroller = Get.find<Authlogincontroller>();
  final ThemeController themeController = Get.find<ThemeController>();
  final CategoryController categoryController = Get.find<CategoryController>();

  List _records = [];

  @override
  void initState() {
    super.initState();
    // 延迟加载数据，确保控制器已初始化
    Future.delayed(const Duration(milliseconds: 500), () {
      loadRecords();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 监听路由变化
    ever(Get.routing.current.obs, (route) {
      if (route == '/home' || route == '/mainpage') {
        loadRecords();
      }
    });
  }

  Future<void> loadRecords() async {
    try {
      print("loadRecords");
      // 检查登录状态和邮箱
      if (!authlogincontroller.isLogin.value) {
        print("User not logged in");
        return;
      }

      final email = authlogincontroller.emailController.text;
      if (email.isEmpty) {
        print("Email is empty");
        return;
      }

      var res = await countController.getCount(email);
      if (res != null && res is List) {
        // 按日期倒序排序
        res.sort((a, b) {
          DateTime dateA = DateTime.parse(a['date']);
          DateTime dateB = DateTime.parse(b['date']);
          return dateB.compareTo(dateA);
        });

        setState(() {
          _records = res;
        });
      } else {
        print("Invalid response format: $res");
        Get.snackbar(
          '提示',
          '暂无数据',
          backgroundColor: Colors.grey.withOpacity(0.1),
          colorText: Colors.grey[600],
          duration: const Duration(seconds: 2),
        );
      }
    } catch (e) {
      print("Error loading records: $e");
      Get.snackbar(
        '提示',
        '加载数据失败，请稍后重试',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final isAllSee = false.obs;
    return Obx(
      () => Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            '记账本',
            style: TextStyle(
              color: themeController.themeColor,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
          actions: [
            IconButton(
              icon: Icon(Icons.file_upload, color: themeController.themeColor),
              onPressed: () => _importCSV(),
            ),
            IconButton(
              icon: Icon(Icons.settings, color: themeController.themeColor),
              onPressed: () => Get.to(() => const SettingsPage()),
            ),
          ],
        ),
        body: Column(
          children: [
            // 月度统计卡片
            isAllSee.value ? SizedBox(height: 10) : _buildStatsCard(context),
            const SizedBox(height: 24),

            // 交易记录标题
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '最近交易',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: themeController.themeColor,
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      isAllSee.value = !isAllSee.value;
                    },
                    child: Text(
                      '查看全部',
                      style: TextStyle(
                        fontSize: 14,
                        // fontWeight: FontWeight.bold,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),

            // 交易记录列表
            _buildRecordList(),
          ],
        ),
      ),
    );
  }

  Widget _verticalTextDivider(BuildContext context, String date) {
    date = date.substring(0, 10);
    double dateTotal = 0;
    _records.forEach((element) {
      if (element['date'].substring(0, 10) == date) {
        // print("33333" + element['amount']);
        dateTotal = dateTotal + double.parse(element['amount']);
      }
    });
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          SizedBox(height: 15),
          Expanded(flex: 4, child: Text(date)),

          Expanded(
            flex: 1,
            child: Text(
              '￥${dateTotal.toStringAsFixed(2)}',
              style: const TextStyle(
                color: Colors.red,
                fontWeight: FontWeight.w900,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget isSameDate(String date1, var set, var record) {
    var bool = false;
    date1 = date1.substring(0, 10);
    if (!set.contains(date1)) {
      bool = true;
      set.add(date1);
    }
    return bool
        ? _verticalTextDivider(context, record['date'])
        : SizedBox(height: 1);
  }

  Widget _buildRecordItem(
    BuildContext context,
    Map<String, dynamic> record,
    var categoryInfo,
  ) {
    return InkWell(
      onTap: () => _showRecordDetails(record),
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(11),
              decoration: BoxDecoration(
                color: themeController.themeColor.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(
                categoryInfo['icon'] as IconData,
                color: themeController.themeColor,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    record['category'],
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  // Text(
                  //   record['date'],
                  //   style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                  // ),
                   Text(
                    record['note']==null||record['note']==''?'':"备注:${record['note']}",
                    style: const TextStyle(
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
            ),
            Text(
              '¥${record['amount']}',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: record['countType'] == 'zhi' ? Colors.red : Colors.green,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecordList() {
    var set = new Set();
    return Expanded(
      child: ListView.builder(
        itemCount: _records.length,
        itemBuilder: (context, index) {
          final record = _records[index];
          final categoryInfo = categoryController.categories.firstWhere(
            (cat) => cat['name'] == record['category'],
            orElse: () => {'icon': Icons.category, 'name': record['category']},
          );

          return Column(
            children: [
              isSameDate(record['date'], set, record),
              TDSwipeCell(
                slidableKey: ValueKey(record['id']),
                groupTag: 'records',
                onChange: (direction, open) {
                  print('打开方向：$direction');
                  print('打开状态$open');
                },
                right: TDSwipeCellPanel(
                  extentRatio: 170 / MediaQuery.of(context).size.width,
                  onDismissed: (context) {
                    // 处理滑动删除
                  },
                  children: [
                    TDSwipeCellAction(
                      backgroundColor: TDTheme.of(context).errorColor6,
                      label: '删除',
                      onPressed: (context) async {
                        try {
                          var res = await countController.deleteCount(record);

                          if (res['code'] == 200) {
                            setState(() {
                              _records.removeAt(index);
                            });
                            Get.snackbar(
                              '成功',
                              '删除成功',
                              backgroundColor: themeController.themeColor
                                  .withOpacity(0.1),
                              colorText: themeController.themeColor,
                              duration: const Duration(seconds: 2),
                            );
                          } else {
                            Get.snackbar(
                              '失败',
                              res['msg'] ?? '删除失败',
                              backgroundColor: Colors.red.withOpacity(0.1),
                              colorText: Colors.red,
                              duration: const Duration(seconds: 2),
                            );
                          }
                        } catch (e) {
                          Get.snackbar(
                            '错误',
                            '删除失败: $e',
                            backgroundColor: Colors.red.withOpacity(0.1),
                            colorText: Colors.red,
                            duration: const Duration(seconds: 2),
                          );
                        }
                      },
                    ),
                    TDSwipeCellAction(
                      backgroundColor: TDTheme.of(context).brandColor6,
                      label: '修改',
                      onPressed: (context) {
                        Get.toNamed(
                          '/record',
                          arguments: {
                            "record": record,
                            "index": index,
                            "isEdit": true,
                          },
                        )?.then((_) {
                          loadRecords(); // 返回时刷新数据
                        });
                      },
                    ),
                  ],
                ),
                cell: _buildRecordItem(context, record, categoryInfo),
              ),
            ],
          );
        },
      ),
    );
  }

  void _showRecordDetails(Map<String, dynamic> record) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => TransactionDetailsCard(
        record: record,
        onUpdate: (updatedRecord) {
          loadRecords(); // Refresh the records when updated
        },
        countController: countController,
        themeController: themeController,
      ),
    );
  }

  void _showRepaymentDialog(
    BuildContext context,
    Map<String, dynamic> record,
    Map<String, dynamic> stage,
  ) {
    DateTime selectedDate = DateTime.now();

    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('选择还款时间'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('分期日期: ${stage['stage']}'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () async {
                      final DateTime? picked = await showDatePicker(
                        context: context,
                        initialDate: selectedDate,
                        firstDate: DateTime(2000),
                        lastDate: DateTime(2100),
                      );
                      if (picked != null) {
                        setState(() {
                          selectedDate = picked;
                        });
                      }
                    },
                    child: Text(
                      '选择日期: ${selectedDate.toString().split(' ')[0]}',
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () async {
                    try {
                      // 更新stage数据
                      stage['isBack'] = true;
                      stage['backTime'] = selectedDate.toString().split(' ')[0];

                      // 调用API更新数据
                      var res = await countController.updateStage(
                        record['id'],
                        stage,
                      );

                      if (res['code'] == 200) {
                        Navigator.pop(context); // 关闭日期选择对话框
                        Navigator.pop(context); // 关闭详情对话框
                        loadRecords(); // 刷新数据
                        Get.snackbar(
                          '成功',
                          '还款记录已更新',
                          backgroundColor: Colors.green.withOpacity(0.1),
                          colorText: Colors.green,
                          duration: const Duration(seconds: 2),
                        );
                      } else {
                        Get.snackbar(
                          '失败',
                          res['msg'] ?? '更新失败',
                          backgroundColor: Colors.red.withOpacity(0.1),
                          colorText: Colors.red,
                          duration: const Duration(seconds: 2),
                        );
                      }
                    } catch (e) {
                      Get.snackbar(
                        '错误',
                        '更新失败: $e',
                        backgroundColor: Colors.red.withOpacity(0.1),
                        colorText: Colors.red,
                        duration: const Duration(seconds: 2),
                      );
                    }
                  },
                  child: const Text('确认'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 16, color: Colors.grey)),
          Text(
            value,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  Widget _buildSwiperCell(
    BuildContext context,
    Map<String, dynamic> record,
    int index,
  ) {
    var screenWidth = MediaQuery.of(context).size.width;

    return TDSwipeCell(
      slidableKey: ValueKey(record['id']),
      groupTag: 'records',
      onChange: (direction, open) {
        print('打开方向：$direction');
        print('打开状态$open');
      },
      right: TDSwipeCellPanel(
        extentRatio: 170 / screenWidth,
        onDismissed: (context) {
          // 处理滑动删除
        },
        children: [
          TDSwipeCellAction(
            backgroundColor: TDTheme.of(context).errorColor6,
            label: '删除',
            onPressed: (context) async {
              try {
                var res = await countController.deleteCount(record);

                if (res['code'] == 200) {
                  setState(() {
                    _records.removeAt(index);
                  });
                  Get.snackbar(
                    '成功',
                    '删除成功',
                    backgroundColor: const Color(0xFF2D9596).withOpacity(0.1),
                    colorText: const Color(0xFF2D9596),
                    duration: const Duration(seconds: 2),
                  );
                } else {
                  Get.snackbar(
                    '失败',
                    res['msg'] ?? '删除失败',
                    backgroundColor: Colors.red.withOpacity(0.1),
                    colorText: Colors.red,
                    duration: const Duration(seconds: 2),
                  );
                }
              } catch (e) {
                Get.snackbar(
                  '错误',
                  '删除失败: $e',
                  backgroundColor: Colors.red.withOpacity(0.1),
                  colorText: Colors.red,
                  duration: const Duration(seconds: 2),
                );
              }
            },
          ),
          TDSwipeCellAction(
            backgroundColor: TDTheme.of(context).brandColor6,
            label: '修改',
            onPressed: (context) {
              Get.toNamed(
                '/record',
                arguments: {"record": record, "index": index, "isEdit": true},
              )?.then((_) {
                loadRecords(); // 返回时刷新数据
              });
            },
          ),
        ],
      ),
      cell: ListTile(
        title: Row(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: (record['countType'] == 'zhi'
                        ? Colors.red
                        : themeController.themeColor)
                    .withOpacity(0.1),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                record['countType'] == 'zhi' ? '支出' : '收入',
                style: TextStyle(
                  color:
                      record['countType'] == 'zhi'
                          ? Colors.red
                          : themeController.themeColor,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(width: 8),
            Text(record['category'] as String),
          ],
        ),
        subtitle: Text(record['date'] as String),
        trailing: Text(
          '¥${record['amount']}',
          style: TextStyle(
            color:
                record['countType'] == 'zhi'
                    ? Colors.red
                    : themeController.themeColor,
            fontWeight: FontWeight.bold,
            fontSize: 16,
          ),
        ),
      ),
    );
  }

  void _showEditDialog(
    BuildContext context,
    Map<String, dynamic> record,
    int index,
  ) {
    final TextEditingController categoryController = TextEditingController(
      text: record['category'],
    );
    final TextEditingController amountController = TextEditingController(
      text: record['amount'].toString(),
    );
    String selectedType = record['countType'] == 'zhi' ? '支出' : '收入';

    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('修改记录'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 支出/收入选择
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildTypeButton('支出', selectedType == '支出', (type) {
                        setState(() {
                          selectedType = type;
                        });
                      }),
                      const SizedBox(width: 20),
                      _buildTypeButton('收入', selectedType == '收入', (type) {
                        setState(() {
                          selectedType = type;
                        });
                      }),
                    ],
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: categoryController,
                    decoration: const InputDecoration(
                      labelText: '分类',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: amountController,
                    keyboardType: const TextInputType.numberWithOptions(
                      decimal: true,
                    ),
                    decoration: const InputDecoration(
                      labelText: '金额',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () async {
                    try {
                      final updatedRecord = {
                        ...record,
                        'category': categoryController.text,
                        'amount': double.parse(amountController.text),
                        'countType': selectedType == '支出' ? 'zhi' : 'shou',
                      };

                      var res = await countController.edit(updatedRecord);

                      if (res['code'] == 200) {
                        setState(() {
                          _records[index] = updatedRecord;
                        });
                        Navigator.pop(context);
                        Get.snackbar(
                          '成功',
                          '修改成功',
                          backgroundColor: const Color(
                            0xFF2D9596,
                          ).withOpacity(0.1),
                          colorText: const Color(0xFF2D9596),
                          duration: const Duration(seconds: 2),
                        );
                        // 立即刷新数据
                        loadRecords();
                      } else {
                        Get.snackbar(
                          '失败',
                          res['msg'] ?? '修改失败',
                          backgroundColor: Colors.red.withOpacity(0.1),
                          colorText: Colors.red,
                          duration: const Duration(seconds: 2),
                        );
                      }
                    } catch (e) {
                      Get.snackbar(
                        '错误',
                        '修改失败: $e',
                        backgroundColor: Colors.red.withOpacity(0.1),
                        colorText: Colors.red,
                        duration: const Duration(seconds: 2),
                      );
                    } finally {
                      loadRecords();
                    }
                  },
                  child: const Text('保存'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildTypeButton(
    String type,
    bool isSelected,
    Function(String) onTap,
  ) {
    return InkWell(
      onTap: () => onTap(type),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFF2D9596) : Colors.grey[50],
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? const Color(0xFF2D9596) : Colors.grey[300]!,
            width: 1,
          ),
        ),
        child: Text(
          type,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey[600],
            fontSize: 16,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget getshouru() {
    {
      final themeController = Get.find<ThemeController>();
      final currentMonth = DateTime.now().month;
      final currentYear = DateTime.now().year;
      // print("getshourucurrentMonth:$currentMonth");
      // print("getshouru_records:$_records");
      final totalIncome = _records
          .where(
            (count) =>
                count['countType'] == 'shou' &&
                DateTime.parse(count['date']).month == currentMonth
                &&DateTime.parse(count['date']).year == currentYear,
          )
          .fold<double>(
            0,
            (sum, count) =>
                sum + (double.tryParse(count['amount'].toString()) ?? 0),
          );
      return Text(
        '¥${totalIncome.toStringAsFixed(2)}',
        style: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
          color: themeController.themeColor,
        ),
      );
    }
  }

  // 统计卡片组件
  Widget _buildStatsCard(BuildContext context) {
    final themeController = Get.find<ThemeController>();
    final isSee = true.obs;
    final eyeIcon = Rx<Icon>(Icon(Icons.remove_red_eye, color: Colors.black));

    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 2,
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          // 月度总览
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(24),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${DateTime.now().month}月总览',
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            color: themeController.themeColor,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '本月收支情况',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                    InkWell(
                      onTap:(){
                       Get.toNamed('/myaccount');
                      } ,
                      child: Icon(Icons.account_box),
                    ),
                    
                    
                    Obx(
                      () => InkWell(
                        onTap: () {
                          isSee.value = !isSee.value;
                          eyeIcon.value =
                              isSee.value
                                  ? Icon(
                                    Icons.visibility_off,
                                    color: Colors.black,
                                  )
                                  : Icon(
                                    Icons.remove_red_eye,
                                    color: Colors.black,
                                  );
                        },
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            shape: BoxShape.circle,
                          ),
                          child: eyeIcon.value,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(
                                Icons.arrow_upward,
                                color: Colors.green,
                                size: 16,
                              ),
                              const SizedBox(width: 4),
                              const Text(
                                '收入',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Obx(() {
                            return isSee.value
                                ? getshouru()
                                : Text(
                                  "¥*****",
                                  style: TextStyle(
                                    color: themeController.themeColor,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                  ),
                                );
                          }),
                        ],
                      ),
                    ),
                    Container(width: 1, height: 40, color: Colors.grey[200]),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(
                                Icons.arrow_downward,
                                color: Colors.red,
                                size: 16,
                              ),
                              const SizedBox(width: 4),
                              const Text(
                                '支出',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Obx(() {
                            final currentMonth = DateTime.now().month;
                            final currentYear = DateTime.now().year;
                            final totalExpense = _records
                                .where(
                                  (count) =>
                                      count['countType'] == 'zhi' &&
                                      DateTime.parse(count['date']).month ==
                                          currentMonth&&DateTime.parse(count['date']).year == currentYear,
                                )
                                .fold<double>(
                                  0,
                                  (sum, count) =>
                                      sum +
                                      (double.tryParse(
                                            count['amount'].toString(),
                                          ) ??
                                          0),
                                );
                            return isSee.value
                                ? Text(
                                  '¥${totalExpense.toStringAsFixed(2)}',
                                  style: TextStyle(
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                    color: themeController.themeColor,
                                  ),
                                )
                                : Text(
                                  "¥*****",
                                  style: TextStyle(
                                    color: themeController.themeColor,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                  ),
                                );
                          }),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 进度条
          Container(
            height: 8,
            margin: const EdgeInsets.symmetric(horizontal: 24),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              children: [
                Expanded(
                  flex: 3,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          themeController.themeColor,
                          themeController.themeColor.withOpacity(0.8),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(4),
                    ),
                  ),
                ),
                Expanded(flex: 2, child: Container()),
              ],
            ),
          ),
          const SizedBox(height: 16),
          // 记一笔按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            child: Container(
              height: 56,
              width: double.infinity,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    themeController.themeColor,
                    themeController.themeColor.withOpacity(0.8),
                  ],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: themeController.themeColor.withOpacity(0.3),
                    spreadRadius: 1,
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: ElevatedButton(
                onPressed: () {
                  Get.toNamed("/record");
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.transparent,
                  shadowColor: Colors.transparent,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.add_circle_outline, color: Colors.white),
                    const SizedBox(width: 8),
                    const Text(
                      '记一笔',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildCloseChartTabs() {
    return SizedBox(height: 1);
  }

  // 图表切换标签
  Widget _buildChartTabs() {
    return SizedBox(
      height: 200,
      child: PageView(
        children: [
          // 饼状图占位
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  spreadRadius: 2,
                  blurRadius: 12,
                ),
              ],
            ),
            child: const Center(child: Icon(Icons.pie_chart, size: 48)),
          ),
          // 折线图占位
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  spreadRadius: 2,
                  blurRadius: 12,
                ),
              ],
            ),
            child: const Center(child: Icon(Icons.show_chart, size: 48)),
          ),
        ],
      ),
    );
  }

  void _showAddRecordDialog() {
    String category = '';
    String amount = '';
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('记一笔'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                decoration: InputDecoration(labelText: '分类'),
                onChanged: (v) => countController.categoryController.text = v,
              ),
              TextField(
                decoration: InputDecoration(labelText: '金额'),
                keyboardType: TextInputType.number,
                onChanged: (v) => countController.amountController.text = v,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                try {
                  var resMsg = countController.check(
                    countController.amountController.text,
                    countController.categoryController.text,
                  );
                  print('resMsg:${resMsg}');
                  if (resMsg.isNotEmpty) {
                    Get.snackbar('失败', resMsg);
                    return;
                  }

                  countController.dateController.text = DateTime.now()
                      .toString()
                      .substring(0, 16);

                  // 先执行异步操作
                  var res = await countController.saveCount();
                  print('res type: ${res.runtimeType}');
                  print('res content: $res');

                  // 然后在 setState 中更新 UI
                  setState(() {
                    _records.insert(0, {
                      'category': countController.categoryController.text,
                      'amount': countController.amountController.text,
                      'date': countController.dateController.text,
                    });
                  });

                  if (res['code'] == 200) {
                    Get.snackbar('成功', '记账成功');
                    Navigator.of(context).pop(); // 关闭对话框
                  } else {
                    Get.snackbar('失败', '记账失败: ${res['message'] ?? '未知错误'}');
                  }
                } catch (e) {
                  print('Error: $e');
                  Get.snackbar('错误', '保存失败: $e');
                }
              },
              child: Text('保存'),
            ),
          ],
        );
      },
    );
  }

  /// 导入CSV文件
  Future<void> _importCSV() async {
    try {
      final importService = ImportService();
      final result = await importService.importCSV();
      
      if (result['success']) {
        // 显示导入结果
        String message = result['message'];
        if (result['errors'] != null && (result['errors'] as List).isNotEmpty) {
          message += '\n\n错误详情:\n${(result['errors'] as List).take(5).join('\n')}';
          if ((result['errors'] as List).length > 5) {
            message += '\n... 还有更多错误';
          }
        }
        
        Get.dialog(
          AlertDialog(
            title: const Text('导入结果'),
            content: SingleChildScrollView(
              child: Text(message),
            ),
            actions: [
              TextButton(
                onPressed: () => Get.back(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
        
        // 刷新数据
        loadRecords();
      } else {
        Get.snackbar(
          '导入失败',
          result['message'],
          backgroundColor: Colors.red.withOpacity(0.1),
          colorText: Colors.red,
          duration: const Duration(seconds: 3),
        );
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '导入过程中发生错误: $e',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 3),
      );
    }
  }
}
